<template>
  <div ref="scroll">
    <slot></slot>
  </div>
</template>

<script >
    import BScroll from 'better-scroll'
    const DIRECTION_H = 'horizontal'
    const DIRECTION_V = 'vertical'
    const MAX_BORDER_NUM = 50
    export default {
        props: {
            // 有时候我们需要知道滚动的位置 为 1 的时候，会非实时 probeType 为 2 的时实时的派发 scroll 事件 
            probeType: {
                type: Number,
                default: 1
            },
            // 是否需要点击事件
            click: {
                type: Boolean,
                default: false
            },
            // 外部数据
            data: {
                type: Array,
                default: null
            },
            // 是否需要监听滚动底部后派发事件通过
            pullup: {
                type: Boolean,
                default: false
            },
            pullUpLoad: {
                type: Boolean,
                default: false
            },
            // 当前滚动方向
            direction: {
                type: String,
                default: DIRECTION_V
            },

        },
        mounted() {
            // 必须要在mounted钩子初始化 DOM渲染之后 不然报错
            setTimeout(() => {
                this.fnInitScroll()
            }, 20)
        },
    methods: {
      fnInitScroll() {
        if (!this.$refs.scroll) {
          return
        }
        this.scroll = new BScroll(this.$refs.scroll, {
          probeType: this.probeType,
          click: this.click,
          eventPassthrough: this.direction === DIRECTION_V ? DIRECTION_H : DIRECTION_V
        })
        // 滚动结束后派发事件
        if (this.pullup) {
          this.scroll.on('scrollEnd', () => {
            if (this.scroll.y <= (this.scroll.maxScrollY + MAX_BORDER_NUM)) {
              this.$emit('scrollToEnd')
            }
          })
        }
        this.scroll.on('scroll', (pos) => {
          if(pos.y >30){
            this.$emit('scroll')
          }
        })
        if(this.pullUpLoad) {
          this.scroll.on('touchEnd', (pos) => {
            if(pos.y >30){
              this.$emit('touchEnd')
            }
          })
        }
      },
      refresh() {
        this.scroll && this.scroll.refresh()
      },
      scrollTo() {
        this.scroll && this.scroll.scrollTo.apply(this.scroll, arguments)
      },
      
    },
    watch: {
      data() {
        setTimeout(() => {
          this.refresh()
        }, this.refreshDelay)
      }
    }
  }
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">

</style>
